<?php
require '../model/Db.php';
$Db = Db::getInstance();
$admin_data = $Db->isadmin();
if(!$admin_data){
	$user_data = $Db->islogin();
	if($user_data['job'] == 3){
		$admin_data = $user_data;
	}
}
if(($admin_data || $user_data['job'] != 0) && is_numeric($_GET['id'])){
    setcookie('curr_zone',$_GET['id'],time()+3600,'/nsbbs/admin/');
	if($user_data){
		$zids_arr  = json_decode($user_data['follow_me'])->zids;
		if(in_array($_GET['id'], $zids_arr)){
			$zone_man = true;
		}
	}
	$module_list = [];
	$kind_data = $Db->find([
		table => ['kind'],
		where => "zid = {$_GET['id']} order by sort,id"
	]);
	foreach ($kind_data as $key => $value) {
		if($admin_data || $zone_man){
			$action = "<span class='btn' id='{$value['id']}'>删除</span>";
		}else{
			$action = '';
		}
		$kind_list .= <<<list
			<li><input type="number" value="{$value['sort']}" class="sort" min="0"> {$value['name']} {$action}</li>
list;
	}
	$module_data = $Db->find([
		table => [module => 'a',kind => 'b'],
		field => 'a.name mname,a.id,b.name kname,a.manager',
		where => "a.kid = b.id and a.zid = {$_GET['id']}"
	]);
	foreach ($module_data as $module_item) {
		$uids = json_decode($module_item['manager'])->uids;
		$uids = implode(',', $uids);
		$u_data = $Db->find([
			table => ['bbs_user'],
			field => 'id,user',
			where => "id in ({$uids}) "
		]);
		$module_item['manager'] = [];
		if($u_data){
			foreach ($u_data as $u_item) {
				$module_item['manager'][] = $u_item;
			}
		}
		$module_list[] = $module_item;
	}
	$module_list = $Db->tohtml($module_list);
	foreach($module_list as $item){
		$ismanager = false;
		$li = '';
		foreach ($item['manager'] as $v) {
			if($v['id'] == $user_data['id']){
				$ismanager = true;
			}
			$li .= <<<li
				<li><a target="_blank" href="/userinfo.php?uid={$v['id']}">{$v['user']}</a></li>	
li;
		}
		if($admin_data || $zone_man || $ismanager){
			$td = <<<td
			<a href="?p=6&q=2&id={$item['id']}">修改</a>&nbsp;<span class="btn" id="{$item['id']}">删除</span>
td;
		}else{
			$td = '无权限';
		}
		$html .= <<<tr
				<tr>
					<td>{$item['mname']}</td>
					<td>{$item['kname']}</td>
					<td>
						<ul>
							{$li}
						</ul>
					</td>
					<td>
						{$td}
					</td>
				</tr>
tr;
	}
	if(!$html){
		$html = '空空如也';
	}
	if($kind_list){
		$kind_list .= '<li><button id="sort">排序</button></li>';
	}
	$div = '';
	if($admin_data || $zone_man){
		$div = <<<div
		<div class="l">
			<p class="tt">添加从版面</p>
			<input type="text" id="name"><button id="add">添加</button>
		</div>
		<div class="l">
			<p class="tt">添加分类</p>
			<input type="text" id="name2"><button id="add2">添加</button>
		</div>
div;
	}
	$kind_list = '<li>(*) 默认面版</li>'.$kind_list;
	echo json_encode([html => $html,li => $kind_list,div => $div]);
}else{
	http_response_code(404);
	echo '<h1 style="color:#337ab7">千呼万唤始出来,犹抱琵琶半遮面</h1>';
}